package so.sao.code.service.infrastructure.filters;

import org.springframework.beans.factory.annotation.Autowired;
import so.sao.code.service.infrastructure.SessionContext;
import so.sao.log.feign.util.WebUtil;
import so.sao.sso.common.CommonConstants;
import so.sao.sso.feign.dto.UserDTO;
import so.sao.top.core.util.mapper.JsonMapper;
import so.sao.top.core.util.wrapper.CoreHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * Created by Administrator on 2017/9/15.
 */
@WebFilter(filterName = "applicationContextFilter", urlPatterns = "/*")
public class InitContextFilter implements Filter {

    @Autowired
    JsonMapper jsonMapper;
    @Autowired
    SessionContext context;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //定时任务没有user默认-1
        if (((CoreHttpServletRequestWrapper) servletRequest).getRequestURI().equals("/portal/rangeActivation/task")) {
            UserDTO user = new UserDTO();
            user.setId(-1L);
            context.CURRECT_USER = user;
        } else {
            String value = ((HttpServletRequest) servletRequest).getHeader(CommonConstants.CURRENT_USER);
            try {
                context.CURRECT_USER = jsonMapper.fromJson(URLDecoder.decode(value, "UTF-8"), UserDTO.class);
            } catch (Exception e) {
//            	e.printStackTrace();
            }
        }
        context.ip = WebUtil.getIpAddr((HttpServletRequest) servletRequest);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
